const http = require('http');

// 测试服务器连接
function testServerConnection() {
    return new Promise((resolve, reject) => {
        const options = {
            hostname: 'localhost',
            port: 3000,
            path: '/api/devices',
            method: 'GET'
        };

        const req = http.request(options, (res) => {
            let data = '';
            
            res.on('data', (chunk) => {
                data += chunk;
            });
            
            res.on('end', () => {
                try {
                    const response = JSON.parse(data);
                    resolve({
                        status: res.statusCode,
                        data: response,
                        headers: res.headers
                    });
                } catch (error) {
                    reject(new Error('响应解析失败: ' + error.message));
                }
            });
        });

        req.on('error', (error) => {
            reject(new Error('请求失败: ' + error.message));
        });

        req.setTimeout(5000, () => {
            req.destroy();
            reject(new Error('请求超时'));
        });

        req.end();
    });
}

// 测试Socket.io连接
function testSocketConnection() {
    return new Promise((resolve, reject) => {
        const io = require('socket.io-client');
        
        const socket = io('http://localhost:3000');
        
        const timeout = setTimeout(() => {
            socket.disconnect();
            reject(new Error('Socket连接超时'));
        }, 5000);

        socket.on('connect', () => {
            clearTimeout(timeout);
            socket.disconnect();
            resolve('Socket.io连接成功');
        });

        socket.on('connect_error', (error) => {
            clearTimeout(timeout);
            reject(new Error('Socket.io连接失败: ' + error.message));
        });
    });
}

// 主测试函数
async function runTests() {
    console.log('=======================================');
    console.log('安卓投屏客户端连接测试');
    console.log('=======================================');
    console.log('');

    try {
        // 测试HTTP API
        console.log('1. 测试HTTP API连接...');
        const apiResult = await testServerConnection();
        console.log('✅ HTTP API连接成功');
        console.log(`   状态码: ${apiResult.status}`);
        console.log(`   响应头: ${JSON.stringify(apiResult.headers, null, 2)}`);
        console.log('');

        // 测试Socket.io连接
        console.log('2. 测试Socket.io连接...');
        const socketResult = await testSocketConnection();
        console.log('✅ Socket.io连接成功');
        console.log(`   结果: ${socketResult}`);
        console.log('');

        console.log('=======================================');
        console.log('🎉 所有测试通过！应用运行正常');
        console.log('=======================================');
        console.log('');
        console.log('请在浏览器中访问: http://localhost:3000');
        console.log('确保已连接安卓设备并开启USB调试模式');

    } catch (error) {
        console.log('=======================================');
        console.log('❌ 测试失败');
        console.log('=======================================');
        console.log(`错误: ${error.message}`);
        console.log('');
        console.log('请检查:');
        console.log('1. 应用是否已启动 (npm start)');
        console.log('2. 端口3000是否被占用');
        console.log('3. 防火墙设置');
        console.log('4. 依赖是否正确安装');
    }
}

// 运行测试
if (require.main === module) {
    runTests().catch(console.error);
}

module.exports = { testServerConnection, testSocketConnection, runTests }; 